Uec3.SalePartPropSearchWindow = Ext.extend(Ext.Window, {
	initPanel : function(initParams) {
		// 来源下拉框
		this.sourceType_store = getDictionaryStore(RES_PATH, {
					group : 'part_source'
				});
		this.source_cmb = getDictionaryComboBox(this.sourceType_store, 'local',
				'part_source', '来源', 'source', 90);
				
		this.sourceType_store.load();
		
		this.source_cmb1 = Uec3.App.dictionary.getCombo("part_source", {showWhole:true, width:80, hiddenName : 'source'});
		
		this.form = this.createForm();
		this.store = this.createStore();
		this.grid = this.createGrid();
		this.join_panel = this.createPanel();
		this.add(this.join_panel);
		
		Ext.util.Observable.capture(this.store, function(e) {
			if (e == 'load') {
				this.checkIsRecordSelected( );
			}
		}.createDelegate(this));
			
		//窗口出来之后触发
		this.on('show',function() {
			
			Ext.Ajax.request({
				url : RES_PATH + '/partner/getPartnerByIdAndOwnerId.do',
				params : {'id' : this.partnerId},
				success : function(res) {
					this.discount = Ext.decode(res.responseText).discount;
					this.store.load();
				}.createDelegate(this)
			});
			
		}, this, {single : true});
		
		this.show();
		
	},
	checkIsRecordSelected : function() {
		var recs = this.store.getRange();
		for (var i = 0; i < recs.length; i++) {
			var rec = recs[i];
			var saleRecs = this.saleStore.getRange();
			for(var j = 0; j < saleRecs.length; j++) {
				var saleRec = saleRecs[j];
				if (rec.data.code + '&' + rec.data.source + '' == saleRec.data.code + '&' + saleRec.data.source + '') {
					rec.set('is_selected', "是");
					rec.set('orderQty', saleRec.data.orderQuantity);
					rec.set('realQty', saleRec.data.quantity);
				}
			}
		}
	},
	// private
	moduleActionHtml : function(moduleId, action, value) {
		
		var record = this.store.getById(value);
		var disp1 = '';
		var disp2 = 'none';
		var realQty = record.get('realQty') + '';
		if(record.get('is_selected') && (record.get('is_selected')+'').trim() == '是' && realQty.trim() != '') {
			disp1 = 'none';
			disp2 = '';
		}
		
		var partPropSearchWindow = "Uec3.App.getDesktop().getWindow('partPropSearchWindow')";
		
		var add = "<a style='font-size:12px;display:" + disp1 + "' href=javascript:" + partPropSearchWindow + "." 
			+ action.func1 + "(" + value + "); >" + action.desc1 + "</a>";
			
		var remove = "<a style='font-size:12px;display:" + disp2 + "' href=javascript:" + partPropSearchWindow + "." 
			+ action.func2 + "(" + value + "); >" + action.desc2 + "</a>";
			
		return add + remove;
	},
	moduleActionRenderer : function(actions) {
		var ref = this;
		if (Ext.isArray(actions)) {
			return function(value, cellmeta, record, rowIndex, columnIndex, store) {
				var html = "";
				for (var i = 0; i < actions.length; i++) {
					var v = value;
					if (actions[i].reader) {
						v = actions[i].reader(value, cellmeta, record, rowIndex, columnIndex, store);
					}
					html += ref.moduleActionHtml(ref.creator.id, actions[i], v) + "&nbsp;&nbsp;";
				}
				return html;
			};
		} else {
			return function(value, cellmeta, record, rowIndex, columnIndex, store) {
				var v = value;
				if (actions.reader) {
					v = actions.reader(value, cellmeta, record, rowIndex, columnIndex, store);
				}
//				alert(record);
				return ref.moduleActionHtml(ref.creator.id, actions, v);
			};
		}
	},
	createForm : function() {
		return {

			style : 'padding:0px;fontSize:13px;',
			layout : 'hbox',
			width : 1010,
			heigth : 80,
			items : [

					{
						xtype : 'label',
						text : '编码:',
						style : {
							marginLeft : '1px',
							width : '50px'
						}
					}, {
						xtype : 'textfield',
						name : 'code_wildcard',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'label',
						text : '名称:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'name_wildcard',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'label',
						text : '车型:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'carModel_wildcard',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'label',
						text : '来源:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, this.source_cmb1, {
						xtype : 'label',
						text : '品牌:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'brand',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'label',
						text : '产地:',
						style : {
							marginLeft : '20px',
							width : '65px'
						}
					}, {
						xtype : 'textfield',
						name : 'origin_wildcard',
						style : {
							width : '70px'
						}
					}, {
						xtype : 'button',
						text : '查    找',
						width : 60,
						style : {
							marginLeft : '30px'
						},
						listeners : {
							click : function() {

								var params = this.join_panel.getForm().getValues();
								for(var i in params) {
									params[i] = castNoSelToNULL(params[i]);
								}
								
								params = Ext.util.JSON.encode(params);
								
								this.store.baseParams = {'queryParam' : params};

								this.store.load();
								
							}.createDelegate(this)
						}

					}
				]
		};
	},
	createStore : function() {
		var record = Ext.data.Record.create([
			{
				name : 'id'
			}, {
				name : 'orderQty'
			}, {
				name : 'realQty'
			}, {
				name : 'retailPrice'
			}, {
				name : 'discount'
			}, {
				name : 'price'
			}, {
				name : 'is_selected'
			}, {
				name : 'code'
			}, {
				name : 'name'
			}, {
				name : 'carModel'
			}, {
				name : 'source'
			}, {
				name : 'measurementUnit'
			}, {
				name : 'brand'
			}, {
				name : 'origin'
			}, {
				name : 'onHand'
			}, {
				name : 'level1Id'
			}, {
				name : 'level1Name'
			}, {
				name : 'level2Name'
			}, {
				name : 'partId'
			}, {
				name : 'partCategoryId'
			}, {
				name : 'durability'
			}
		]);
		
		return new Ext.data.JsonStore({
			url : RES_PATH + "/part/queryOwnerCompPartProperties.do",
			mode : "local",
			root : "root",
			totalProperty : "totalProperty",
			idProperty : "id",
			pruneModifiedRecords : true,
			fields : record
		});
		
		
	},
	getSaleRecord : function(_record) {
		var data = _record.data
		var purData = {};

		purData.name = data.name;
		purData.code = data.code;
		purData.source = data.source;
		purData.measurementUnit = data.measurementUnit;
		purData.brand = data.brand;
		purData.origin = data.origin;
		purData.retailPrice = data.retailPrice;
//		purData.discount_show = this.discount + '%';
		purData.discount = this.discount;
		purData.price = Ext.util.Format.number((this.discount/100) * (data.retailPrice), '0.00');
		purData.level1Name = data.level1Name;
		purData.level2Name = data.level2Name;
		purData.level1Id = data.level1Id;
		purData.partId = data.partId;
		purData.partCategoryId = data.partCategoryId;
		purData.durability = data.durability;
//		purData.inventoryIdBySeller = data.inventoryId;
		purData.carModel = data.carModel;
		purData.orderQuantity = data.orderQty;
		purData.quantity = data.realQty;
		var record = new this.saleRecord(purData);
		
		return record;
	},
	validateSale : function(rcd) {
		var records = this.saleStore.getRange();
		for (var i = 0; i < records.length; i++) {
			var rec = records[i];
			if (rec.data.code + '&' + rec.data.source + '' == rcd.data.code + '&' + rcd.data.source + '') {
				Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR, '对不起，该行记录您已经选择..');
				return false;
			}
		}
		
		if(!rcd.get('realQty') || (rcd.get('realQty')+'').trim() == '') {
			Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR, '对不起，您的实际数量不可以为空..');
			return false;
		}
		
		if((rcd.get('realQty')+'').trim() == '0') {
			Ext.Msg.alert(PurChaseAlert.PROMOTE_ERROR, '对不起，您的实际数量不可以为0..');
			return false;
		}
		
		return true;
	},
	partClickToAdd : function(id) {
		
		var record = this.store.getById(id);
		
		if (!this.validateSale(record)) {
			return;
		}

		record.set('is_selected', '是');
		var saleRecord = this.getSaleRecord(record);

		var index = this.saleStore.getCount();
	
		this.saleStore.insert(index, saleRecord);
		
		var td = this.grid.getView().getCell(this.store.indexOf(record), this.grid.getColumnModel().getIndexById('exec'));
		var addA = Ext.get(td).select('a').elements[0];
		addA.style.display = 'none';
		var removeA = Ext.get(td).select('a').elements[1];
		removeA.style.display = '';
	},
	partClickToCancel : function(id) {
		var record = this.store.getById(id);
		record.set('is_selected', '');
		record.set('orderQty', '');
		record.set('realQty', '');
		var records = this.saleStore.getRange();
		for (var i = 0; i < records.length; i++) {
			var rec = records[i];
			if (rec.data.code + '&' + rec.data.source + '' == record.data.code + '&' + record.data.source + '') {
				this.saleStore.remove(rec);
				return ;
			}
		}
		
		var removeA = Ext.get(td).select('a').elements[1];
		removeA.style.display = 'none';
		var addA = Ext.get(td).select('a').elements[0];
		addA.style.display = '';
	},
	createGrid : function() {
		this.colName = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
				{
					header : '订购数量',
					dataIndex : 'orderQty',
					editor : new Ext.form.NumberField({
						regex : /([1-9][0-9]*(\.\d+)?)|(0\.\d+)/,
						regexText : '您只能够输入数字'
					}),
					sortable : true
				}, {
					header : '销售数量',
					dataIndex : 'realQty',
					editor : new Ext.form.NumberField({
						regex : /([1-9][0-9]*(\.\d+)?)|(0\.\d+)/,
						regexText : '您只能够输入数字'
					}),
					sortable : true
				}, {
					header : '已选中',
					dataIndex : 'is_selected'
				}, {
					header : '操作',
					id : 'exec',
					dataIndex : 'id',
					renderer : this.moduleActionRenderer({
						func1 : 'partClickToAdd',
						desc1 : '选择',
						func2 : 'partClickToCancel',
						desc2 : '取消'
					})
				}, {
					header : '零件编码',
					dataIndex : 'code',
					sortable : true
				}, {
					header : '零件名称',
					dataIndex : 'name'
				}, {
					header : '车型',
					dataIndex : 'carModel',
					sortable : true
				}, {
					header : '来源',
					dataIndex : 'source',
					renderer : Ext.util.Format.comboRenderer(this.source_cmb),
					sortable : true
				}, {
					header : '单位',
					dataIndex : 'measurementUnit'
				}, {
					header : '品牌',
					dataIndex : 'brand',
					sortable : true
				}, {
					header : '产地',
					dataIndex : 'origin',
					sortable : true
				}, {
					header : '媒体价',
					dataIndex : 'retailPrice'
				}, {
					header : '折扣',
					dataIndex : 'discount',
					renderer : this.getDiscount.createDelegate(this)
				}, {
					header : '折后价',
					dataIndex : 'price',
					renderer : this.getPrice.createDelegate(this)
				}, {
					header : '库存',
					dataIndex : 'onHand'
				}
			]);
			
		var c = 0;
				
		// 创建grid，装载明细数据
		return new Ext.grid.EditorGridPanel({
			style : {padding : '2px'},
			height : 300,
			clicksToEdit : 1,
			store : this.store,
			iconCls : 'icon-grid',
			loadMask : {
				msg : '数据加载中...'
			},
			viewConfig : {
				forceFit : true
			},
			cm : this.colName,
			bbar : new Ext.PagingToolbar({
				pageSize : purOrSaleOrderPageSize,
				store : this.store,
				displayInfo : true,
				displayMsg : '第 {0} - {1} 条  共 {2} 条',
				emptyMsg : "没有记录"
			}),
			listeners : {
				'validateedit' : function(e) {
					if((e.value + '').trim() == '') {
						return false;
					}
				},
				'afteredit': function(e) {
					if(e.field == 'orderQty' || e.field == 'realQty') {
						var qty = e.record.get(e.field) + '';
						if(e.record.get('is_selected') && (e.record.get('is_selected')+'').trim() != '' && (e.record.get('realQty')+'').trim() != '') {
							
							var records = this.saleStore.getRange();
							for (var i = 0; i < records.length; i++) {
								var rec = records[i];
								if (rec.data.code + '&' + rec.data.source + '' == e.record.data.code + '&' + e.record.data.source + '') {
									if(e.field == 'orderQty') {
										rec.set('orderQuantity', qty);
									} else if(e.field == 'realQty') {
										rec.set('quantity', qty);
									} else {}
									return ;
								}
							}
						}
					}
				}.createDelegate(this),
				'mouseout' : function() {
					if(this.activeEditor) {
						c++;
						if(c == 2) {
							c = 0;
							this.stopEditing();
						}
					}
				}

			}
		});
	},
	getDiscount : function() {
		return this.discount + '%';
	},
	getPrice : function(value, cellmeta, record, rowIndex, columnIndex, store) {
		return Ext.util.Format.number((this.discount/100) * (record.get('retailPrice')), '0.00');
	},
	createPanel : function() {
		return new Ext.FormPanel({
			frame : true,
			height : 180,
			items : [this.form,
					this.grid]
		});
	}
});

Uec3.SalePartPropSearchWindowCreator = Ext.extend(Ext.app.Module, {
	id : 'salePartPropSearchWindowCreator',
	type : 'common/notepad',
	createWindow : function(initParams) {
		var desktop = this.app.getDesktop();
		var main_win = desktop.getWindow('salePartPropSearchWindow');
		if( !main_win ) {
			main_win = desktop.createWindowNoTask({
				id : 'partPropSearchWindow',
				modal : true,
				title : '[ESC退出] 查询零件库存',
				width : 980,
				height : 370,
				iconCls : 'acc-icon',
				animCollapse : false,
	            constrainHeader : true,
	            maximizable : false,
	            minimizable : false,
				taskbuttonTooltip : '查询零件库存',
				layout : "fit"
			}, Uec3.SalePartPropSearchWindow);
		}
		
		main_win.saleGrid = initParams.saleGrid ;
		main_win.saleStore = main_win.saleGrid.getStore();
		main_win.saleRecord = initParams.saleRecord;
		main_win.partnerId = initParams.partnerId;
		
		main_win.creator = this;
		main_win.versionCode = ++(PurchaseCount.count);
		main_win.initPanel(initParams);
	}
	
});